package data_structures_and_algorithms.slide_window;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Code_0003_lengthOfLongestSubstring
 * @Description: https://leetcode.cn/problems/longest-substring-without-repeating-characters/
 * @Author: yongliang.ma
 * @Create_time:2022/10/28 09:40
 */
public class Code_0003_lengthOfLongestSubstring {


    public int lengthOfLongestSubstring(String s) {
        if (s.length() < 2){
            return s.length();
        }

        // 创建记录字符的出现位置
        Map<Character, Integer> visited = new HashMap<>();

        int max = 0, pre = 0;
        for (int i = 0; i < s.length(); i++) {
            if (visited.containsKey(s.charAt(i))){
                Integer lastIndex = visited.get(s.charAt(i));
                if (i - pre > lastIndex){
                    pre++;
                }else {
                    pre = i - lastIndex;
                }
            }else {
                pre++;
            }
            max = Math.max(pre, max);
            // 更新字符位置
            visited.put(s.charAt(i), i);
        }
        return max;
    }



}
